package cn.itcast.demo.mq.topic;

import cn.itcast.demo.mq.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static cn.itcast.demo.mq.topic.SendDemo.EXCHANGE_NAME;
import static cn.itcast.demo.mq.topic.SendDemo.QUEUE2_NAME;

/**
 * @author 虎哥
 */
public class ReceiveDemo2 {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 建立连接
        Connection connection = ConnectionUtils.getConnection();
        // 获取通道Channel
        Channel channel = connection.createChannel();
        // 创建队列
        channel.queueDeclare(QUEUE2_NAME, true, false, false, null);
        // 绑定交换机
        channel.queueBind(QUEUE2_NAME, EXCHANGE_NAME, "#.news");

        // 创建一个Consumer消费者
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 获取消息体
                String msg = new String(body);
                // 处理消息
                System.out.println("消费者2接收消息：" + msg);
                // 消息的手动确认
                channel.basicAck(envelope.getDeliveryTag(),true);
            }
        };

        // 消费消息，指定消息队列、消费消息的回调函数
        channel.basicConsume(QUEUE2_NAME, false, consumer);
    }
}
